package algorithm.sort;

import org.junit.Test;

import java.util.Arrays;

/**
 * Description TODO
 *
 * @ClassName algorithm.sort.SelectionSort
 * @Version 1.0
 * @Date: 2022/2/14 10:53
 * @Author xuyi
 */
public class SelectionSort {
    @Test
    public void test1(){
        int[] arr = new int[]{1,5,3,4,2};
        sort2(arr);
        System.out.println(Arrays.toString(arr));
    }


    public void sort(int[] arr){
        for(int i=0; i<arr.length-1; i++){
            int minValue = Integer.MAX_VALUE;
            int minIndex = i;
            for(int j=i+1;j<arr.length; j++){
                if(arr[j] < minValue){
                    minValue = arr[j];
                    minIndex = j;
                }
            }
            if(minIndex!=i){
                swap(arr,i,minIndex);
            }
        }
    }

    public void sort2(int[] arr){
        for(int i=0; i<arr.length-1; i++){
            int minIndex = i;
            for(int j=i+1;j<arr.length; j++){
                if(arr[j] < arr[minIndex]){
                    minIndex = j;
                }
            }
            if(minIndex!=i){
                swap(arr,i,minIndex);
            }
        }
    }

    private void swap(int[] arr,int i,int j){
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
